<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
class Register extends CI_Controller{
	public function __construct() {
		parent::__construct ();
		$this->load->model("user_model");
		$this->load->model('category_model');
		$whereArr = array("status"=>1);
		$this->category_list = $this->category_model->resultAll($whereArr);
	}
	/*
	 *加载注册页面
	 */
	public function index(){
		$data['category_list'] = $this->category_list;
		$this->load->view("register",$data);
	}
	/*
	 * 进行用户注册功能
	 */
	public function reg(){
		$data['username'] = $this->input->post('username');
		$data['email'] = $this->input->post('email');
		$data['telephone'] = $this->input->post('telephone');
		$data['logo'] = $this->input->post('user_logo');
		$data['password'] = $this->input->post('password');
		$data['createtime'] = time();
		$repassword = $this->input->post('repassword');
		$message = array();
		if(!isset($data['logo'])||empty($data['logo'])){
			$message['flag'] = -1;
			$message['content'] = "别闹，你还上传头像呢！";
			echo json_encode($message);
			exit;
		}
		$user_flag = $this->isExistUser($data['username']);
		if($user_flag){
			$message['flag'] = -1;
			$message['content'] = "该用户名已经被注册过，不能再使用!!";
			echo json_encode($message);
			exit;
		}
		$email_flag = $this->isExistEmail($data['email']);
		if($email_flag){
			$message['flag'] = -1;
			$message['content'] = "该邮箱已经被绑定过，不能再使用!!";
			echo json_encode($message);
			exit;
		}
		$data['password'] = $this->_encrypt($data['password']);
		$result = $this->user_model->insert($data);
		if($result){
			$message['flag'] = 1;
			$message['content'] = "注册成功!!";
			$message['url'] = site_url('Login');
			echo json_encode($message);
			exit;
		}else{
			$message['flag'] = -1;
			$message['content'] ="注册失败!!";
			echo json_encode($message);
			exit;
		}
	}
	/*
	 *ajax 图片上传功能 
	 */
	public function upload_user_logo($form_name,$file_size){
		/*$fp = fopen("1.txt","w+");
		fputs($fp,$form_name);
		fclose($fp);*/
		$params = array(
			'form_name'=>$form_name,
			'upload_dir'=>'./data/uploads/user_images',
			'file_size'=>$file_size
		);
		$this->load->library("AjaxUpload",$params);
	}
	/*
	 *根据用户名查找该用户是否已经注册 
	 */
	public function isExistUser($username){
		$whereArr = array("username"=>$username);
		$username_row = $this->user_model->row($whereArr);
		if($username_row){
			return true;
		}else{
			return false;
		}
	}
	/*
	 *根据邮箱账号查找该邮箱是否已经使用过 
	 */
	public function isExistEmail($email){
		$whereArr = array("email"=>$email);
		$email_row = $this->user_model->row($whereArr);
		if($email_row){
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 密码加密
	 */
	private function _encrypt($str) {
		$this->load->library ( 'encrypt' );
		$re = $this->encrypt->encode ( $str );
		return $re;
	}
}